const express = require('express');
const router = express.Router();
const sql = require('../db/index');

// 获取分页栏目信息列表
router.get('/category', async (req, res) => {
  let { page = 1, pageSize = 10 } = req.query;
  page = parseInt(page);
  pageSize = parseInt(pageSize);
  let start = (page - 1) * pageSize;
  try {
    // 获取总记录数
    const [totalRows] = await sql.query('SELECT COUNT(*) as count FROM jz_product_category');
    const total = totalRows[0].count;

    // 获取分页数据
    const [rows] = await sql.query(`SELECT * FROM jz_product_category LIMIT ?, ?`, [start, pageSize]);
    res.send({
      code: 200,
      msg: '获取栏目信息列表成功',
      data: {
        total,
        page,
        pageSize,
        list: rows
      }
    });
  } catch (error) {
    res.send({
      code: 500,
      msg: '获取栏目信息列表失败',
      error: error.message
    });
  }
});

// 添加栏目信息
router.post('/category/add', async (req, res) => {
  const { name, icon, num, parent_id } = req.body;
  try {
    const [result] = await sql.query('INSERT INTO jz_product_category (name, icon, num, parent_id) VALUES (?, ?, ?, ?)', [name, icon, num, parent_id]);
    res.send({
      code: 200,
      msg: '添加栏目信息成功',
      data: { id: result.insertId }
    });
  } catch (error) {
    res.send({
      code: 500,
      msg: '添加栏目信息失败',
      error: error.message
    });
  }
});

// 更新栏目信息
router.put('/category/:id', async (req, res) => {
  const { id } = req.params;
  const { name, icon, num, parent_id } = req.body;
  try {
    await sql.query('UPDATE jz_product_category SET name = ?, icon = ?, num = ?, parent_id = ? WHERE id = ?', [name, icon, num, parent_id, id]);
    res.send({
      code: 200,
      msg: '更新栏目信息成功'
    });
  } catch (error) {
    res.send({
      code: 500,
      msg: '更新栏目信息失败',
      error: error.message
    });
  }
});

// 删除栏目信息
router.delete('/category/:id', async (req, res) => {
  let { id } = req.params;
  id = +id
  try {
    // 检查该栏目下是否有商品
    const [products] = await sql.query('SELECT * FROM jz_product WHERE product_category_id = ?', [id]);
    if (products.length > 0) {
      return res.send({
        code: 400,
        msg: '删除失败，栏目下存在商品'
      });
    }
    // 如果没有商品，删除栏目
    await sql.query('DELETE FROM jz_product_category WHERE id = ?', [id]);
    res.send({
      code: 200,
      msg: '删除栏目信息成功'
    });
  } catch (error) {
    res.send({
      code: 500,
      msg: '删除栏目信息失败',
      error: error.message
    });
  }
});

module.exports = router;
